package com.atguigu.bigdata.chapter07.state;

import com.atguigu.bigdata.bean.WaterSensor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lzc
 * @Date 2022/9/6 15:03
 */
public class Flink04_Key_Value {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        // 每隔3秒中做一次checkpoint
        // 这样理解: 每隔3秒,把程序的所有的状态做一次持久化, 程序出了问题重启的时候, 可以从持久化状态中恢复数据
        env.enableCheckpointing(3000);
        
        // 在flatMap算子中使用算子状态
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(
                    data[0],
                    Long.valueOf(data[1]),
                    Integer.valueOf(data[2])
                );
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
    
                private ValueState<Integer> lastState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 获取监控状态实例
                    lastState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastState", Integer.class));
                }
    
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
    
                    // 从单值的状态获取值. 第一次来的时候, 状态中肯定没值, 所以返回值是 null
                    Integer lastVc = lastState.value();
                    
                    if (lastVc != null && value.getVc() > 10 && lastVc > 10) {
                        out.collect(ctx.getCurrentKey() + " 的水位连续两次超过10, 发出红色预警...");
                    }
                    
                    // 把当前的值, 赋值到状态
                    lastState.update(value.getVc());
                    
                }
            })
            .print();
    
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
}
